package com.euq.service.Impl;

import com.euq.entity.Dept;
import com.euq.dto.Ret;
import com.euq.mapper.DeptMapper;
import com.euq.node.DeptNode;
import com.euq.service.DeptService;
import com.euq.utils.EuqException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<DeptNode> getDeptTree() {
        List<Dept> allDepts = deptMapper.listAll();
        List<DeptNode> nodeList = allDepts.stream().map(dept -> {
            DeptNode node = new DeptNode();
            BeanUtils.copyProperties(dept, node);
            return node;
        }).collect(Collectors.toList());
        return buildTree(nodeList);
    }
    @Override
    public Dept insert(String simpleName,String fullName,Integer num,Long pid) {
        try{
            if (com.euq.utils.BeanUtils.isOneEmpty(simpleName, fullName, num, pid)) {
                throw new EuqException("9999","参数不能为空");
            }
            Dept dept = deptMapper.findByFullName(fullName);
            if (dept != null) {
                throw new EuqException("9999","部门已存在");
            }
            dept.setPid(pid);
            dept.setNum(num);
            dept.setFullName(fullName);
            dept.setSimpleName(simpleName);
            setDeptPids(dept);
            deptMapper.insert(dept);
            return dept;
        }catch (Exception e) {throw new RuntimeException("新增部门失败", e);}
    }

    @Override
    public Dept update(Dept dept) {
        try{
            setDeptPids(dept);
            deptMapper.update(dept);
            return dept;
        } catch (Exception e) {
            throw new RuntimeException("部门修改失败",e);
        }
    }

    @Override
    public Object deleteById(Long id) {
        if (id==0){
            throw new EuqException("9999","输入ID不能为空");
        }
        Dept dept = deptMapper.findById(id);
        if (dept == null) {
            throw new EuqException("9999","输入Id错误");
        }
        String pids="[" + id + "]";
        deptMapper.deleteLikePids(pids);
        deptMapper.deleteById(id);
        return Ret.success("部门删除成功");
    }

    private List<DeptNode> buildTree(List<DeptNode> nodes) {
        Map<Long, DeptNode> idNodeMap = nodes.stream()
                .collect(Collectors.toMap(DeptNode::getId, Function.identity()));

        List<DeptNode> rootNodes = new ArrayList<>();

        for (DeptNode node : nodes) {
            Long pid = node.getPid();
            if (pid == null || pid == 0) {
                rootNodes.add(node); // 根节点
            } else {
                DeptNode parent = idNodeMap.get(pid);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node); // 添加子节点
                }
            }
        }
        return rootNodes;
    }

    public void setDeptPids(Dept dept) {
        if (dept.getPid() == 0 || dept.getPid() == null) {
            dept.setPids("[0],");
        } else {
            Dept pDept = deptMapper.findByPid(dept.getPid());
            String pids ="";
            if (pDept != null) {
                pids = pDept.getPids();
            }
            dept.setPids(pids+"["+dept.getPid()+"],");

        }
    }
}
